<?php
/**
 * Author: Administrator
 * Date: 2022/7/16 1:39
 */

namespace DesignPatterns\Creation\Pool;


class Processor
{
    protected Pool $pool;
    protected int $processing = 0;
    protected int $maxPorcess = 3;
    protected array $waitingQueue = [];

    public function __construct(Pool $pool)
    {
        $this->pool = $pool;
    }

    public function process($image): void
    {
        if ($this->processing++ < $this->maxPorcess) {
            $this->createWorker($image);
        } else {
            $this->pushWaitingQueue($image);
        }
    }

    public function createWorker($image): void
    {
        $worker = $this->pool->get();
        $worker->run($image, [$this, 'workerDone']);
    }

    public function workerDone($worker): void
    {
        $this->processing--;
        $this->pool->depose($worker);
        if (count($this->waitingQueue) > 0) {
            $this->createWorker($this->popWaitingQueue());
        }
    }

    public function pushWaitingQueue($image): void
    {
        $this->waitingQueue[] = $image;
    }

    public function popWaitingQueue(): int
    {
        return array_unshift($this->waitingQueue);
    }
}